package com.itheima.aop;

import com.itheima.mapper.EmpLoginLogMapper;
import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.*;
import com.itheima.util.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Aspect
@Component
public class LoginAspect {

    @Autowired
    private EmpLoginLogMapper loginLogMapper;

    /*
    找到增强的登录方法
          @PostMapping("/login")
            public Result login(@RequestBody Emp emp){
                log.info("员工登录用户信息:{}",emp);//emp 封装了登录的账户和密码
                // 将封装用户名和密码的emp传递service 需要service返回需要的 登录响应数据
                LoginInfo loginInfo = empService.login(emp);//传递emp 是传递 账户 和 密码
                if(loginInfo != null){//登录成功
                    return Result.success(loginInfo);
                }
                return Result.error("用户名或密码错误~请重新录入");
            }
     */
   @Around("execution(* com.itheima.controller.LoginController.login(..))")
   public Object around(ProceedingJoinPoint pjp) throws Throwable{
       log.info("对登录信息进行记录....");
       //获取登录时 填写的用户名和密码--在参数位置 Emp类型里面 封装
       Object[] args = pjp.getArgs();
       Emp emp = (Emp) args[0];
       String username = emp.getUsername();
       String password = emp.getPassword();

       //登录时间
       LocalDateTime loginTime = LocalDateTime.now();

       long begin = System.currentTimeMillis(); //方法执行前计时
       //调用原始方法  得到返回的对象
       Object obj = pjp.proceed();

       long end = System.currentTimeMillis();//方法执行后计时

       Result result = (Result) obj;

       //获取登录是否成功
       Short isSuccess = result.getCode().shortValue();
       //jwt
       String jwt = "";
       if (isSuccess == 1){ //成功
           Object data = result.getData();
           LoginInfo loginInfo = (LoginInfo) data;
           jwt = loginInfo.getToken();
       }

       //记录登录日志
       EmpLoginLog loginLog = new EmpLoginLog(null, username, password, loginTime, isSuccess, jwt, end-begin);
       loginLogMapper.insert(loginLog);

       return obj;
   }
}
